<script lang="ts" setup>
import { reactive, ref, watch, toRefs } from "vue"
import { ElTable, ElMessageBox, FormInstance, type FormRules, ElMessage } from "element-plus"
// import { ElTable, FormInstance, type FormRules, ElMessage } from "element-plus"
// 接口
import {
  createPoolDataApi,
  updatePoolDataApi,
  getPoolDataApi,
  listProductYk,
  getShopDataApi,
  deletePoolDataApi
} from "@/api/xinghai"
import { type getTeamData } from "@/api/team/types/team"
import { usePagination } from "@/hooks/usePagination"
import { Search, Refresh } from "@element-plus/icons-vue"
const loading = ref(true)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
defineOptions({
  name: "WebProductSet"
})
const DATA = reactive<any>({
  formData: { details: "" }
})
const { formData } = toRefs(DATA)
const formRef = ref<FormInstance | null>(null)
const dialogVisible = ref<boolean>(false)
const rules: FormRules = reactive({
  xhPoolName: [{ required: true, message: "协议名称不能为空", trigger: "blur" }],
  goodId: [{ required: true, message: "请选择系统套餐", trigger: "blur" }],
  shopId: [{ required: true, message: "请填写淘宝店铺ID", trigger: "blur" }],
  shopName: [{ required: true, message: "请填写淘宝店铺名称", trigger: "blur" }],
  teamName: [{ required: true, message: "请选择团队", trigger: "blur" }],
  xhPoolId: [{ required: true, message: "请填写号池ID", trigger: "blur" }],
  appKey: [{ required: true, message: "请填写AppKey", trigger: "blur" }]
})
const addProduct = () => {
  dialogVisible.value = true
  resetForm()
  formData.value = {}
}

// #region 改
const teamId = ref<undefined | string>(undefined)
const handleUpdate = (row: any) => {
  teamId.value = row.id
  formData.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}
// #endregion

// #region  删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`您确定要删除:${row.xhPoolName}吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deletePoolDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getList()
    })
  })
}
// #endregion

// #region 增
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (teamId.value === undefined) {
        createPoolDataApi(formData.value).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getList()
        })
      } else {
        updatePoolDataApi(formData.value).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getList()
        })
      }
    } else {
      return false
    }
  })
}

const resetForm = () => {
  teamId.value = undefined
  formRef.value?.resetFields()
  formData.value.sku = ""
  clearValidate()
}
// #endregion
// #region 查
const tableTotal = ref<number>()
const tableData = ref<getTeamData[]>([])
const getList = () => {
  getPoolDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    name: searchData.xhPoolName
  })
    .then((res: any) => {
      tableData.value = res.data.list
      tableTotal.value = res.data.total
      loading.value = false
    })
    .catch(() => {
      tableData.value = []
      loading.value = false
    })
}
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  xhPoolName: ""
})
const searchDataTc = reactive<any>({
  type: ""
})
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getList()
    console.log("重置")
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getList()
    console.log("查询")
  }
  paginationData.currentPage = 1
}
/**套餐优卡 */
const goodsList = ref<any>([])
const getGoods = async () => {
  loading.value = true
  await listProductYk({ type: searchDataTc.type })
    .then((res: any) => {
      goodsList.value = res.data
    })
    .finally(() => {
      loading.value = false
    })
}
getGoods()
/** 店铺列表 */
const shopList = ref<any>([])
const getShop = async () => {
  await getShopDataApi({ page: 1, size: 1000 }).then((res: any) => {
    shopList.value = res.data.list
  })
}
getShop()
// #endregion
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getList, { immediate: true })
const clearValidate = () => {
  formRef.value?.clearValidate()
}
// #region 所有团队
import { useTeamStore } from "@/store/modules/team"
const teamStore = useTeamStore()
const tableDataB = ref<any[]>([])
teamStore.getTeamFn()
watch(
  [() => teamStore.teamListStore],
  (newValue) => {
    tableDataB.value = newValue.flat()
  },
  { immediate: true }
)

const formatterGoods = (row: any, column: any, celValue: any) => {
  goodsList.value.filter((item: any) => {
    if (item.id === row.goodId) {
      celValue = item.name
    }
  })
  return celValue
}
const chooseShop = (val: any) => {
  // console.log(val)
  shopList.value.filter((item: any) => {
    if (item.shopId === val) {
      formData.value.shopName = item.shopName
    }
  })
}

const changeType = (val: any) => {
  if (val !== "本地") {
    formData.value.goodId = ""
  } else {
    formData.value.goodId = 0
  }
}
watch(
  [() => formData.value.sku],
  (newValue) => {
    searchDataTc.type = newValue.flat()[0]
    getGoods()
  },
  {
    immediate: true
  }
)
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="xhPoolName" label="号池名称">
          <el-input v-model.trim="searchData.xhPoolName" clearable placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 中间部分 -->
    <el-card v-loading="loading" shadow="never">
      <!-- 顶部添加职位 -->
      <div class="middle-top">
        <div>
          <el-button type="primary" @click="addProduct">添加号池</el-button>
        </div>
      </div>
      <!-- 中间渲染内容 -->
      <div class="table-center">
        <el-table :data="tableData">
          <el-table-column label="ID" align="center" prop="id" :show-overflow-tooltip="true" />
          <el-table-column label="号池名称" align="center" prop="xhPoolName" :show-overflow-tooltip="true" />
          <el-table-column label="号池ID" align="center" prop="xhPoolId" :show-overflow-tooltip="true" />
          <el-table-column label="AppKey" align="center" prop="appKey" :show-overflow-tooltip="true" />
          <el-table-column
            label="系统套餐"
            align="center"
            prop="goodId"
            :show-overflow-tooltip="true"
            :formatter="formatterGoods"
          />
          <el-table-column label="淘宝店铺ID" align="center" prop="shopId" :show-overflow-tooltip="true" />
          <el-table-column label="淘宝店铺" align="center" prop="shopName" :show-overflow-tooltip="true" />
          <el-table-column label="团队" align="center" prop="teamName" :show-overflow-tooltip="true" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="tableTotal"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="teamId === undefined ? '新增' : '修改'" @close="resetForm" width="60%">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="号池名称" prop="xhPoolName" label-width="120">
          <el-input v-model="formData.xhPoolName" placeholder="请输入号池名称" />
        </el-form-item>
        <el-form-item label="号池ID" prop="xhPoolId" label-width="120">
          <el-input v-model="formData.xhPoolId" placeholder="请输入号池ID" />
        </el-form-item>
        <el-form-item label="AppKey" prop="appKey" label-width="120">
          <el-input v-model="formData.appKey" placeholder="请输入AppKey" />
        </el-form-item>
        <el-form-item label="团队" prop="teamName" label-width="120">
          <el-select v-model="formData.teamName" filterable clearable style="width: 100%">
            <el-option v-for="item in tableDataB" :key="item.id" :label="item.name" :value="item.name"
          /></el-select>
        </el-form-item>
        <el-form-item label="号卡类型" prop="sku" label-width="120">
          <el-select v-model="formData.sku" filterable style="width: 100%" @change="changeType">
            <el-option key="流量卡" label="流量卡" value="流量卡" />
            <el-option key="靓号" label="靓号" value="靓号" />
            <el-option key="本地" label="本地" value="本地" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.sku !== '本地'" label="系统套餐" label-width="120" prop="goodId">
          <el-select v-model="formData.goodId" clearable style="width: 100%" placeholder="套餐来源优卡掌厅系统">
            <el-option v-for="item of goodsList" :label="item.name" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-else label="系统套餐" label-width="120" prop="goodId">
          <el-input v-model="formData.goodId" disabled />
        </el-form-item>
        <el-form-item label="淘宝店铺" prop="shopId" label-width="120">
          <el-select v-model="formData.shopId" clearable style="width: 100%" @change="chooseShop">
            <el-option v-for="item of shopList" :label="item.shopName" :value="item.shopId" :key="item.shopId" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="淘宝店铺名称" prop="shopName" label-width="120">
                    <el-input v-model="form.shopName" placeholder="请输入店铺名称" />
                </el-form-item> -->
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
// .box-card {
//   height: 70px;
//   margin-bottom: 20px;
// }
.search-wrapper {
  margin-bottom: 20px;
}
.middle-top {
  margin-bottom: 20px;
}
.table-center {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
